<template>
  <view class="app-layout">
    <app-header title="申请退款" />
    <view class="app-main">

      <view class="refund-container" @click.prevent="handlePageClick">
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%">
            <view class="steps-container">
              <view class="step-wrap">
                <view class="step-item">
                  <view class="step-icon">
                    <image src="../../static/imgs/one.png" mode=""></image>
                  </view>
                  <view class="step-text" :class="{ active: currentStep==0 }">退款申请</view>
                </view>
                <view class="step-line"></view>
                <view class="step-item">
                  <view class="step-icon">
                    <image src="../../static/imgs/two.png" mode=""></image>
                  </view>
                  <view class="step-text">退款审核</view>
                </view>
                <view class="step-line"></view>
                <view class="step-item">
                  <view class="step-icon">
                    <image src="../../static/imgs/three.png" mode=""></image>
                  </view>
                  <view class="step-text">退款成功</view>
                </view>
              </view>
            </view>
            <view class="info-tit"> 基本信息 </view>
            <view class="refund-form">
              <uni-row :gutter="20">
                <uni-col :span="12">
                  <view class="flex-row">
                    <view class="order-label">
                      退款单号
                    </view>
                    <view class="order-num">
                      *
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="flex-row">
                    <view class="order-label">
                      门店名称
                    </view>
                    <view class="order-name">
                      Mocup coffee {{orderDetail?.deptName}}
                    </view>
                  </view>
                </uni-col>

              </uni-row>
              <uni-row :gutter="20">
                <uni-col :span="12">
                  <view class="flex-row">
                    <view class="order-label">
                      会员信息
                    </view>
                    <view class="order-name">
                      {{orderDetail?.buyerName}} {{orderDetail?.phone}}
                    </view>
                  </view>
                </uni-col>
                <uni-col :span="12">
                  <view class="flex-row">
                    <view class="order-label">
                      订单编号
                    </view>
                    <view class="order-name">
                      {{orderDetail?.orderId}}
                    </view>
                  </view>
                </uni-col>

              </uni-row>
              <uni-row :gutter="20">
                <uni-col :span="12">
                  <view class="flex-row">
                    <view class="order-label">
                      退款类型
                    </view>
                    <view class="order-name">
                      <u-radio-group v-model="formData.deliveryMethod" @change="groupChange">
                        <u-radio label="整单退" :name="0" />
                        <u-radio label="部分退款" :name="1" />
                      </u-radio-group>
                    </view>
                  </view>
                </uni-col>
              </uni-row>
            </view>
            <view class="info-tit"> 退款商品 </view>
            <view class="refund-form">
              <uni-table border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th align="left">商品</uni-th>
                  <uni-th align="left" :width="100">单价</uni-th>
                  <uni-th align="left" :width="100">订单数量</uni-th>
                  <uni-th align="left" :width="100">实付金额</uni-th>
                  <uni-th align="left" :width="180">
                  <view class="" style="position: relative;">
                    退款数量
                    <image src="../../static/imgs/icon.png" mode="" class="icon-con" @click.stop="toggleTooltips">
                    </image>
                    <view class="tooltip-box" :class="{ show: isTooltipShows }" ref="tooltipRef">
                      <view class="tooltip-content">退款数量仅适用于整杯/份商品的退款。若仅涉及小料、配料或定制项的退款，无须填写数量。</view>
                      <view class="tooltip-arrow"></view>
                    </view>
                  </view>
                  </uni-th>
                  <uni-th align="left" :width="180">
                    <view class="" style="position: relative;">
                      退款金额
                      <image src="../../static/imgs/icon.png" mode="" class="icon-con" @click.stop="toggleTooltip">
                      </image>
                      <view class="tooltip-box" :class="{ show: isTooltipShow }" ref="tooltipRef">
                        <view class="tooltip-content">未发生退款的商品，无需填写退款金额</view>
                        <view class="tooltip-arrow"></view>
                      </view>
                    </view>
                  </uni-th>
                </uni-tr>
                <uni-tr v-for="item in tabList" :key="item">
                  <uni-td>
                    <view style="display: flex;align-items: center;">
                      <image :src="item.mainImage" mode="" style="width:32px;height: 32px;margin-right:5px"></image>
                      <view class="">
                        <view class="">
                          {{item.name}}

                        </view>
                        <view class="plain" v-if="item.productCombo">
                          {{item.productCombo}}
                        </view>
                      </view>
                    </view>
                  </uni-td>
                  <uni-td>{{item.basePrice}}</uni-td>
                  <uni-td>{{item.productQuantity}}</uni-td>
                  <uni-td>{{item.itemPrice}}</uni-td>
                  <!-- 可申请退款${item.productQuantity}件 -->
                  <uni-td> <uni-easyinput :placeholder="`请输入`" type="digit" clearable
                      v-model="item.quantity" v-if="formData.deliveryMethod==1"></uni-easyinput>
                    <text v-if="formData.deliveryMethod==0"> {{item.quantity}}</text></uni-td>
                  <uni-td>
                    <!-- 可申请退款${item.itemPrice}元 -->
                    <uni-easyinput :placeholder="`请输入`" type="digit" clearable v-model="item.money"
                      v-if="formData.deliveryMethod==1"></uni-easyinput>
                    <text v-if="formData.deliveryMethod==0"> {{item.money}}</text>
                  </uni-td>

                </uni-tr>
              </uni-table>
              <view class="total-con">
                <view class="total" v-if="orderDetail?.sceneCode=='takeout'&&formData.deliveryMethod==0">
                  配送费：￥{{orderDetail?.deliveryFee}}
                </view>
                <view class="total">
                  退款合计：
                  <text>￥{{totalRefund}}</text>
                </view>
              </view>
            </view>
            <view class="info-tit"><text class="start">* </text> 退款原因 </view>
            <view class="refund-form" style="padding-bottom: 26px;">
              <u-textarea v-model="formData.reason" :placeholder="'请输入'" :maxlength="200" :rows="5" :autosize="true"
                count></u-textarea>
              <view class="instructions">
                <view class="label">
                  退款说明：
                </view>
                <view class="name">
                  <text>发生订单级整单退款后无法进行再次申请退款操作。</text>
                  <text>
                    退款执行后会按比例回收发放的积分。</text>
                  <text> 订单中全部金额退款后，订单状态变更【已取消】，并退还订单中使用的积分、优惠券等资产</text>
                </view>
              </view>
            </view>


          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

      <u-popup :show="show" @close="popupCancel" :round="10" mode="center">
        <view class="popup-cons">
          <view class="applyfor-image">
            <image src="../../static/imgs/success.png" mode=""></image>
          </view>
          <view class="applyfor-green">
            退款申请提交成功
          </view>
          <view class="applyfor-info">
            可在【订单】-【售后订单】审核退款信息完成退款
          </view>
          <view class="button-group">
            <!-- <button class="cancel-btn" @click="popupCancel">取消</button> -->
            <button class="pay-btn" @click="popupSure">去退款</button>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    computed
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getOrder,
    applySubmit
  } from '@/requests/apis/order'
  let show = ref(false)
  let tabList = ref([])
  let orderDetail = ref()
  const tooltipRef = ref(null)
  let formData = ref({
    deliveryMethod: 0
  })
  const currentStep = ref(0)
  onLoad(async (e) => {
    if (e.orderId) {
      console.log(e.orderId)
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      let res = await getOrder({
        orderId: e.orderId
      })
      orderDetail.value = res.Result
      tabList.value = res.Result.orderItemList
      tabList.value.forEach((item) => {
        item['quantity'] = item.productQuantity
        item['money'] = item.itemPrice
      })
        uni.hideLoading()
    }
  })

const totalRefund = computed(() => {
  // 1. 计算商品退款总和（放大100000倍处理精度）
  const totalTenThousandth = tabList.value.reduce((sum, item) => {
    const amount = Number(item.money) || 0;
    return sum + Math.round(amount * 100000);
  }, 0);

  // 2. 判断是否需要加配送费（deliveryMethod === 0 时）
  let deliveryFeeAdd = 0;
  if (formData?.value.deliveryMethod === 0) {
    // 配送费同样放大100000倍处理精度
    const deliveryFee = Number(orderDetail?.value.deliveryFee) || 0;
    deliveryFeeAdd = Math.round(deliveryFee * 100000);
  }

  // 3. 总和 = 商品退款总和 + 配送费（如需），再缩小100000倍
  return (totalTenThousandth + deliveryFeeAdd) / 100000;
});


  // 控制提示框显示状态
  const isTooltipShow = ref(false)
  const isTooltipShows = ref(false)

  // 点击图标：切换提示框显示/隐藏
  const toggleTooltip = () => {
    isTooltipShow.value = !isTooltipShow.value
     isTooltipShows.value = false
  }
  const toggleTooltips = () => {
    isTooltipShows.value = !isTooltipShows.value
    isTooltipShow.value = false
  }
  const handlePageClick = (e) => {
    isTooltipShow.value = false
    isTooltipShows.value = false
  }
  const close = () => {
    uni.navigateBack()
  }

  const groupChange=(e)=>{
    console.log(e,'eeeeee')
    if(e==1){
      tabList.value.forEach((item) => {
        item['quantity'] = undefined
        item['money'] = undefined
      })
    }else {
      tabList.value.forEach((item) => {
        item['quantity'] = item.productQuantity
        item['money'] = item.itemPrice
      })
    }
  }

  function validateRefundItems() {
      const list = tabList.value;
      let hasValidItems = false; // 存在有效商品
      let hasError = false; // 存在单条错误

      for (const item of list) {
        // 1. 提取当前商品的退款数量、金额
        const refundQty = item.quantity;
        const refundAmt = item.money;

        // 2. 判断“数量是否填写”“金额是否填写”
        const isQtyFilled = refundQty !== '' && refundQty != null;
        const isAmtFilled = refundAmt !== '' && refundAmt != null;

          if (isAmtFilled) {
              const amtStr = String(refundAmt); // 转为字符串处理
              const decimalPart = amtStr.split('.')[1]; // 获取小数部分
              if (decimalPart && decimalPart.length > 2) { // 小数位数超过2位
                hasError = true;
                uni.showToast({
                  title: '退款金额最多只能输入两位小数',
                  icon: 'none',
                  duration: 2000
                });
                return false;
              }
            }

        // 3. 核心校验：金额/数量必须为“正数”（>0）
        // 新增负数校验：不仅不能为0，还不能小于0
        const isAmtValid = isAmtFilled ? Number(refundAmt) > 0 : true;
        const isQtyValid = isQtyFilled ? Number(refundQty) > 0 : true;

        // 4. 错误提示细化（区分零值和负数）
        if (isAmtFilled && Number(refundAmt) <= 0) {
          hasError = true;
          // 区分“零”和“负数”的提示
          const msg = Number(refundAmt) < 0 ? '退款金额不能为负数' : '退款金额不能为0';
          uni.showToast({ title: msg, icon: 'none', duration: 2000 });
          return false;
        }
        if (isQtyFilled && Number(refundQty) <= 0) {
          hasError = true;
          // 区分“零”和“负数”的提示
          const msg = Number(refundQty) < 0 ? '退款数量不能为负数' : '退款数量不能为0';
          uni.showToast({ title: msg, icon: 'none', duration: 2000 });
          return false;
        }

        // 5. 数量填写时，金额必须填写且有效（原有逻辑保留）
        if (isQtyFilled && !isAmtFilled) {
          hasError = true;
          uni.showToast({
            title: '填写退款数量后，退款金额必须填写',
            icon: 'none',
            duration: 2000
          });
          return false;
        }

        // 6. 标记当前商品是否有效
        const currentItemIsValid =
          (isAmtFilled && isAmtValid) || // 仅金额填且为正数
          (isQtyFilled && isAmtFilled && isAmtValid && isQtyValid); // 数量+金额都填且合法
        if (currentItemIsValid) {
          hasValidItems = true;
        }
      }

      // 7. 全局校验：至少有一条有效商品
      if (!hasValidItems) {
        uni.showToast({
          title: '请至少填写一条商品的退款金额',
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      return !hasError;
    }
  // function validateRefundItems() {
  //   const list = tabList.value;
  //   let hasValidItems = false; // 是否存在“有效输入项（非空、非0）”
  //   let hasError = false; // 是否存在“数量/金额只填一个，或值为0”的错误

  //   for (const item of list) {
  //     // 校验“退款数量”
  //     const refundQty = item.quantity;
  //     const isQtyValid =
  //       refundQty !== '' && // 非空字符串
  //       refundQty != null && // 非 null/undefined
  //       Number(refundQty) !== 0; // 数值不等于 0

  //     // 校验“退款金额”
  //     const refundAmt = item.money; // 假设退款金额字段为 money
  //     const isAmtValid =
  //       refundAmt !== '' &&
  //       refundAmt != null &&
  //       Number(refundAmt) !== 0;

  //     // 判断“有效输入”与“错误场景”
  //     if (isQtyValid || isAmtValid) {
  //       hasValidItems = true; // 标记“存在至少一项有效输入”

  //       // 数量和金额必须**同时有效（非空、非0）**
  //       if (!isQtyValid || !isAmtValid) {
  //         let errMsg = '';
  //         if (!isQtyValid && isAmtValid) {
  //           errMsg = '退款数量不能为空且不能为 0';
  //         } else if (isQtyValid && !isAmtValid) {
  //           errMsg = '退款金额不能为空且不能为 0';
  //         } else {
  //           errMsg = '退款数量和金额必须同时填写且不能为 0';
  //         }
  //         hasError = true;
  //         uni.showToast({
  //           title: errMsg,
  //           icon: 'none',
  //           duration: 2000 // 延长提示时间，确保用户看清
  //         });
  //         return false; // 单项错误，立即终止校验
  //       }
  //     }
  //   }

  //   // 全局校验（是否有有效输入项）
  //   if (!hasValidItems) {
  //     uni.showToast({
  //       title: '请选择至少一项商品，并填写退款数量/金额（不能为 0）',
  //       icon: 'none',
  //       duration: 2000
  //     });
  //     return false;
  //   }

  //   return !hasError; // 无错误则返回 true
  // }
  // 提交
  const submit = async () => {
    console.log(formData.value.reason, 'formData.value.reason')

    const isItemsValid = validateRefundItems();
    if (!isItemsValid) {
      return; // 商品项校验失败，终止后续逻辑
    }
    if (formData.value.reason === '' ||
      formData.value.reason === undefined ||
      formData.value.reason === null) {

      uni.showToast({
        title: '请填写退款原因',
        icon: 'none'
      });
      return;
    }
    console.log(tabList.value, 'tabList.value')

    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    const formattedData = tabList.value
      // 过滤掉「退款金额为空」的项
      .filter(item => item.money !== '' && item.money != null)
      // 格式化数据，处理退款数量
      .map(item => ({
        orderItemId: item.itemId,
        quantity: (item.quantity !== '' && item.quantity != null) ?
          item.quantity : 0,
        money: item.money
      }));

    let obj = {
      orderId: orderDetail.value.orderId,
      reason: formData.value.reason,
      type: formData.value.deliveryMethod,
      itemForm: formattedData,
    }

    let res = await applySubmit(obj)
    if (res.ResponseCode == 1) {
      uni.hideLoading()
      show.value = true
    }
    show.value = true
  }
  // 弹窗取消
  const popupCancel = () => {
    show.value = false;
    uni.switchTab({
      url: '/pages/order/index',
    })
  }
  // 弹窗确认
  const popupSure = () => {
    show.value = false
    const app = getApp();
    app.globalData.switchTabParams = {
      type: 'refund'
    };
    // uni.navigateBack()
    uni.switchTab({
      url: '/pages/order/index',
    })
  }
</script>
<style lang="scss" scoped>
  .refund-container {
    margin: 10px 10px 0;
    background: #ffffff;
    border-radius: 10px;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .steps-container {
      display: flex;
      align-items: center;
      padding: 23px 0;
      justify-content: center;
      box-sizing: border-box;

      .step-wrap {
        display: flex;
        align-items: center;
      }

      .step-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .step-icon {
          image {
            width: 36px;
            height: 36px;
          }
        }

        .step-text {
          font-weight: 400;
          font-size: 12px;
          color: #8590B3;
        }
      }

      .active {
        color: #0F90FD !important;
      }

      .step-line {
        flex: 1;
        width: 76px;
        height: 2px;
        border-top: 1px dashed #B6BCD1;
        margin: 0 8px;
      }
    }


    .info-tit {
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      padding-left: 77px;
      box-sizing: border-box;
      margin-bottom: 18rpx;
    }

    .refund-form {
      padding: 0 84px 0;
      box-sizing: border-box;

      .plain {
        padding: 2px 8px;
        background: #F6F6F6;
        border-radius: 8px;
        font-size: 12px;
      }

      .icon-con {
        width: 14px;
        height: 14px;
        vertical-align: middle;
        margin-left: 4px;
      }

      .tooltip-box {
        position: absolute;
        top: 30px;
        left: -22%;
        background: rgba(47, 75, 153, 0.8);
        font-weight: 400;
        font-size: 14px;
        color: #FFFFFF;
        padding: 12px 15px;
        box-sizing: border-box;
        border-radius: 6px;
        z-index: 9999;
        display: none;

        &.show {
          display: block !important;
        }
        .tooltip-content{
          text-align: justify;
        }
      }

      .tooltip-arrow {
        position: absolute;
        top: -6px;
        left: 50%;
        transform: translateX(-50%);
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-top: 6px solid rgba(47, 75, 153, 0.8);
        border-bottom: 6px solid rgba(47, 75, 153, 0.8);
        border-top: none;
      }

      :deep(.uni-row) {
        align-items: center;
        margin-bottom: 28px;
      }

      .order-label {
        white-space: nowrap;
        margin-right: 22px;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
      }

      .order-num {
        height: 40px;
        background: #F6F6F6;
        border-radius: 10px;
        font-weight: 400;
        font-size: 14px;
        color: #999999;
        line-height: 40px;
        width: 100%;
        padding-left: 19rpx;
        box-sizing: border-box;
      }

      .order-name {
        font-weight: 400;
        font-size: 14px;
        color: #333333;
      }

      .total-con {
        display: flex;
        justify-content: flex-end;
        margin: 10px;
        gap: 15px;

        .total {
          font-weight: 400;
          font-size: 14px;
          color: #000000;
          line-height: 20px;

          text {
            font-weight: 500;
            font-size: 14px;
            color: #FF5800;
          }
        }
      }

      .instructions {
        display: flex;
        margin-top: 12px;

        .label {
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
        }

        .name {
          display: flex;
          flex-direction: column;
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
          line-height: 26px;
        }
      }
    }
  }
</style>
